from django.views import View
from rest_framework.views import APIView
from django.http.response import JsonResponse, HttpResponseBadRequest
from casedemo14_userSer.models import CaseDemo14User,CaseDemo14UserRole
from casedemo14_userSer.serializer import CaseDemo14UserSerializerDemo1,CaseDemo14UserRoleSerializerDemo1
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
import json
from django.shortcuts import render
# Create your views here.

class CaseDemo14UserSerializerViewDemo1(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(CaseDemo14UserSerializerViewDemo1, self).dispatch(request, *args, **kwargs)

    def post(self, request):
        try:
            data = json.loads(request.body)
            serializer = CaseDemo14UserSerializerDemo1(data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse({'status': 'ok', 'data': serializer.data})
            else:
                return JsonResponse({'status': 'error', 'data': serializer.errors})
        except Exception as e:
            return JsonResponse({'status': 'error', 'data': str(e)})
    
    def get(self, request):
        try:
            users = CaseDemo14User.objects.all()
            serializer = CaseDemo14UserSerializerDemo1(users, many=True)
            return JsonResponse({'status': 'ok', 'data': serializer.data})
        except Exception as e:
            return JsonResponse({'status': 'error', 'data': str(e)})
        
    def put(self, request):
        try:
            data = json.loads(request.body)
            user_id = data.get('useronlyID')
            if not user_id:
                return HttpResponseBadRequest('缺少参数')
            user = CaseDemo14User.objects.get(useronlyID=user_id)
            serializer = CaseDemo14UserSerializerDemo1(user, data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse({'status': 'ok', 'data': serializer.data})
            else:
                return JsonResponse({'status': 'error', 'data': serializer.errors})
        except Exception as e:
            return JsonResponse({'status': 'error', 'data': str(e)})
    
    def delete(self, request):
        try:
            data = json.loads(request.body)
            user_id = data.get('useronlyID')
            if not user_id:
                return HttpResponseBadRequest('缺少参数')
            user = CaseDemo14User.objects.get(useronlyID=user_id)
            user.delete()
            return JsonResponse({'status': 'ok', 'data': '删除成功'})
        except Exception as e:
            return JsonResponse({'status': 'error', 'data': str(e)})
        





# CaseDemo14UserRoleSerializerDemo1的序列化实现
class CaseDemo14UserRoleSerializerViewDemo1(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(CaseDemo14UserRoleSerializerViewDemo1, self).dispatch(request, *args, **kwargs)
    def post(self, request):
        try:
            data = json.loads(request.body)
            serializer = CaseDemo14UserRoleSerializerDemo1(data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse({'status': 'ok', 'data': serializer.data})
            else:
                return JsonResponse({'status': 'error', 'data': serializer.errors})
        except Exception as e:
            return JsonResponse({'status': 'error', 'data': str(e)})
    
    def get(self, request):
        try:
            roles = CaseDemo14UserRole.objects.all()
            serializer = CaseDemo14UserRoleSerializerDemo1(roles, many=True)
            return JsonResponse({'status': 'ok', 'data': serializer.data})
        except Exception as e:
            return JsonResponse({'status': 'error', 'data': str(e)})
        
    def put(self, request):
        try:
            data = json.loads(request.body)
            role_id = data.get('role')
            if not role_id:
                return HttpResponseBadRequest('缺少参数')
            role = CaseDemo14UserRole.objects.get(role=role_id)
            serializer = CaseDemo14UserRoleSerializerDemo1(role, data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse({'status': 'ok', 'data': serializer.data})
            else:
                return JsonResponse({'status': 'error', 'data': serializer.errors})
        except Exception as e:
            return JsonResponse({'status': 'error', 'data': str(e)})
    
    def delete(self, request):
        try:
            data = json.loads(request.body)
            role_id = data.get('role')
            if not role_id:
                return HttpResponseBadRequest('缺少参数')
            role = CaseDemo14UserRole.objects.get(role=role_id)
            role.delete()
            return JsonResponse({'status': 'ok', 'data': '删除成功'})
        except Exception as e:
            return JsonResponse({'status': 'error', 'data': str(e)})



## 实现role表的创建和获取
class UserRoleSerializerListCreateViewDemo2(View):
    def get(self, request):
        roles = CaseDemo14UserRole.objects.all()
        serializer = CaseDemo14UserRoleSerializerDemo1(roles, many=True)
        return JsonResponse({'status': 'ok', 'data': serializer.data})
    def post(self, request):
        serializer = CaseDemo14UserRoleSerializerDemo1(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({'status': 'ok', 'data': serializer.data})
        return JsonResponse({'status': 'error', 'data': serializer.errors})
    
# 单个用户的crud    
class UserRoleSerializerCRUDViewDemo2(APIView):
    def get_object(self,pk):
        try:
            return CaseDemo14UserRole.objects.get(pk=pk)
        except CaseDemo14UserRole.DoesNotExist:
            return None
    def get(self, request, pk):
        role = self.get_object(pk)
        if not role:
            return JsonResponse({'status': 'error', 'data': '角色不存在'})
        serializer = CaseDemo14UserRoleSerializerDemo1(role)
        return JsonResponse({'status': 'ok', 'data': serializer.data})
    def put(self, request, pk):
        role = self.get_object(pk)
        if not role:
            return JsonResponse({'status': 'error', 'data': '角色不存在'})
        serializer = CaseDemo14UserRoleSerializerDemo1(role, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({'status': 'ok', 'data': serializer.data})
        return JsonResponse({'status': 'error', 'data': serializer.errors})
    def delete(self, request, pk):
        role = self.get_object(pk)
        if not role:
            return JsonResponse({'status': 'error', 'data': '角色不存在'})



# from rest_framework.viewsets import ModelViewSet的作用
"""
ModelViewSet 是 DRF 的 视图集，封装了标准的 CRUD 操作：

GET /students/ → list

GET /students/{id}/ → retrieve

POST /students/ → create

PUT /students/{id}/ → update

DELETE /students/{id}/ → destroy

queryset：控制视图集操作的对象范围

serializer_class：指定用哪个序列化器处理数据的输入输出
"""
from rest_framework.viewsets import ModelViewSet
class UserRoleSerializerViewSetDemo3(ModelViewSet):
    queryset = CaseDemo14UserRole.objects.all()
    serializer_class = CaseDemo14UserRoleSerializerDemo1







## 举例子，创建一个视图，实现对班级的增删改查
from .models import Student, Classroom
from casedemo14_userSer.serializer import StudentSerializer, ClassroomSerializer
# 学生列表与创建
class StudentListCreateView(APIView):
    def get(self, request):
        students = Student.objects.all()
        serializer = StudentSerializer(students, many=True, context={'request': request})
        return JsonResponse({'status': 'ok', 'data': serializer.data})

    def post(self, request):
        serializer = StudentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({'status': 'ok', 'data': serializer.data})
        return JsonResponse({'status': 'error', 'data': serializer.errors})
    

# 班级列表与创建
class ClassroomListCreateView(APIView):
    def get(self, request):
        classrooms = Classroom.objects.all()
        serializer = ClassroomSerializer(classrooms, many=True)
        return JsonResponse({'status': 'ok', 'data': serializer.data})
    def post(self, request):
        serializer = ClassroomSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({'status': 'ok', 'data': serializer.data})
        return JsonResponse({'status': 'error', 'data': serializer.errors})




#  使用 mixin + GenericAPIView 实现视图（views.py）
from rest_framework import generics, mixins
from rest_framework.response import Response
from .models import CaseDemo14UserRole
from .serializer import CaseDemo14UserRoleSerializerDemo4

# 列表 + 创建
class CaseDemo14UserRoleListCreateViewDemo5(mixins.ListModelMixin,
                                       mixins.CreateModelMixin,
                                       generics.GenericAPIView):
    queryset = CaseDemo14UserRole.objects.all()
    serializer_class = CaseDemo14UserRoleSerializerDemo4

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)  # GET -> 列表

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)  # POST -> 创建

# 获取 + 更新 + 删除
class CaseDemo14UserRoleDetailViewDemo5(mixins.RetrieveModelMixin,
                                   mixins.UpdateModelMixin,
                                   mixins.DestroyModelMixin,
                                   generics.GenericAPIView):
    queryset = CaseDemo14UserRole.objects.all()
    serializer_class = CaseDemo14UserRoleSerializerDemo4

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)  # GET /<id>/ -> 详情

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)  # PUT -> 更新

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)  # DELETE -> 删除
